package com.huawang.mdesign.model.service.inter.simulationintegration;

import cn.hutool.json.JSONUtil;
import com.huawang.mdesign.model.service.dto.SimulationContextDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * 仿真集成
 */
@Service
@Primary
@Slf4j
public class SimulationIntegrationService implements SimulationIntegrationInterface {
    @Autowired
    private ApplicationContext applicationContext;
    private SimulationIntegrationInterface currentSimulationIntegrationService;

    private SimulationContextDTO context;

    @PostConstruct
    public void init() {
        Map<String, SimulationIntegrationInterface> dynamicTableOperationMap = new HashMap<>();
        dynamicTableOperationMap.putAll(applicationContext.getBeansOfType(SimulationIntegrationInterface.class));
        if(dynamicTableOperationMap.size() > 1) {
            for(Map.Entry<String, SimulationIntegrationInterface> entry : dynamicTableOperationMap.entrySet()) {
                if(!this.equals(entry.getValue())) {
                    currentSimulationIntegrationService = entry.getValue();
                    break;
                }
            }
        }
    }

    @Override
    public @NotNull Boolean start(Map<String, Object> params) {
        if(currentSimulationIntegrationService != null) {
            return currentSimulationIntegrationService.start(params);
        }
        return Boolean.TRUE;
    }

    @Override
    public @NotNull Boolean pause(Map<String, Object> params) {
        if(currentSimulationIntegrationService != null) {
            return currentSimulationIntegrationService.pause(params);
        }
        return Boolean.TRUE;
    }

    @Override
    public @NotNull Boolean stop(Map<String, Object> params) {
        if(currentSimulationIntegrationService != null) {
            return currentSimulationIntegrationService.stop(params);
        }
        return Boolean.TRUE;
    }

    /**
     * 获取仿真插件执行过的节点
     * @param dto 仿真插件执行过的节点
     * @return 仿真插件执行过的节点
     */
    @Nullable
    public SimulationContextDTO getExecutedNodes(@NotNull SimulationContextDTO dto) {
        synchronized (this) {
            //仿真插件推送
            if (CollectionUtils.isNotEmpty(dto.getExecutedNodes())) {
                log.info("[simulation executed nodes] : {}", JSONUtil.toJsonStr(dto));
                context = dto;
            }

            //前端查询
            return context;
        }
    }
}
